import SparkMD5 from "spark-md5";
import {baseImgUrl} from "@/utils/request";


export let typeMap={model: 3,aiModel: 4}
export function  getNormalPath(p) {
    if (p.length === 0 || !p || p == 'undefined') {
        return p
    };
    let res = p.replace('//', '/')
    if (res[res.length - 1] === '/') {
        return res.slice(0, res.length - 1)
    }
    return res;
}


export  function deepClone(source) {
    if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'deepClone')
    }
    const targetObj = source.constructor === Array ? [] : {}
    Object.keys(source).forEach(keys => {
        if (source[keys] && typeof source[keys] === 'object') {
            targetObj[keys] = deepClone(source[keys])
        } else {
            targetObj[keys] = source[keys]
        }
    })
    return targetObj
}

/**
 * 获取文件的MD5数值
 * @param {*} file
 */
export  function  getUploadFileMD5(file) {
    return new Promise((resolve, reject) => {
        const fileReader = new FileReader();

        fileReader.onload = () => {
            const arrayBuffer = fileReader.result;
            const md5Hash = SparkMD5.ArrayBuffer.hash(arrayBuffer);
            resolve(md5Hash);
        };

        fileReader.onerror = (error) => {
            reject(error);
        };

        fileReader.readAsArrayBuffer(file);
    });
}

export function getImgUrl(val) {
    if(val.startsWith("http")){
        return val;
    }
    return baseImgUrl+val;
}

export const validatePass = (rule, value, callback) => {
    console.log('规则',rule,value)
    if (value !== undefined&&value.length>0) {
        const passRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d!@#$%^&*(),.?":{}|<>]{8,16}$/;
        if (!passRegex.test(value)) {
            callback(new Error('密码8-16个字符，至少1个大写字母，1个小写字母和1个数字'))
        } else {
            callback()
        }
    } else if (rule.required) {
        callback(new Error('密码不能为空'))
    } else {
        callback()
    }
}
